import json
from datetime import datetime

from fastapi.encoders import jsonable_encoder


def custom_datetime_encoder(dt: datetime) -> str:
    time_str = dt.strftime("%Y-%m-%d %H:%M:%S")
    #包含中文时有可能会出错,需要先使用占位符再进行替换
    # time_str = dt.strftime("%Y{Y}%m{m}%d{d} %H{H}%M{M}%S{S}").format(Y='年', m='月', d='日', H='时', M='分', S='秒')
    return time_str

custom_encoder={
    datetime: custom_datetime_encoder,
}

class JSONEncoderDate(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        else:
            return json.JSONEncoder.default(self, obj)


# def json_encoders_deep_root_non_json_encoders(obj):
#     pass

def json_encoders_deep(obj):
    if obj is None:
        return None
    if isinstance(obj, dict):
        return {k: json_encoders_deep(v) for k, v in obj.items()}
    if isinstance(obj, list):
        return [json_encoders_deep(v) for v in obj]
    if isinstance(obj, str):
        return obj
    if isinstance(obj, (int, float)):
        return obj
    if isinstance(obj, datetime):
        return custom_datetime_encoder(obj)
    if hasattr(obj, 'json_encoders'):
        # print(str_prominent('data has json_encoders'))
        return obj.json_encoders()
    # if isinstance(obj,BaseResult):
    # return json_encoders_deep(obj, custom_encoder=custom_encoder)
    if hasattr(obj,'__dict__'):
        return json_encoders_deep(obj.__dict__)
    return jsonable_encoder(obj, custom_encoder=custom_encoder)

def to_json_string(obj,indent=None):
    print(obj)
    # dict = obj
    # if hasattr(obj,'__dict__'):
    #     dict=obj.__dict__
    return json.dumps(json_encoders_deep(obj), ensure_ascii=False, cls=JSONEncoderDate,indent=indent)
